﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using DATN.Common;
using DATN.Entities;

namespace DATN.DataAccess
{
    public class NhanVienDataAccess
    {
        private SqlConnection conn;
        private SqlCommand cmd;
        //Them User
        public bool InsertNhanVien(Nhanvien nhanVien)
        {
            int gioiTinh = 1;
            if(nhanVien.Gioi_tinh==false)
            {
                gioiTinh = 0;
            }

            conn = new SqlConnection(AppConfig.ConnectionString);
            string truyVan = "insert into DSNhanVien(Ma,Ho_dem,Ten,Gioi_tinh,Nam_sinh)"
                                + "values('" + nhanVien.Ma + "','" + nhanVien.Ho_dem + "','"+nhanVien.Ten+"'," + gioiTinh + ",'" + nhanVien.Nam_sinh + "')";
            cmd = new SqlCommand(truyVan, conn);
            conn.Open();
            return cmd.ExecuteNonQuery() > 0;
        }

        public string getLastID(string tableName, string filedName)
        {
            string sql = "SELECT TOP 1 " + filedName + " FROM " + tableName + " ORDER BY " + filedName + " DESC";
            // thực hiện câu truy vấn trên
            DataSet ds = getDataSet(sql);
            return ds.Tables[0].Rows[0][filedName].ToString();
        }

        public DataSet getDataSet(string truyVan)
        {
            DataSet DS = new DataSet();
            if (truyVan != "")
            {
                conn = new SqlConnection(AppConfig.ConnectionString);
                cmd = new SqlCommand(truyVan, conn);
                conn.Open();
                SqlDataAdapter da = new SqlDataAdapter(truyVan, conn);
                da.Fill(DS);
                conn.Close();
            }
            return DS;
        }

        public string NextID(string lastID, string prefixID)
        {
            if (lastID == "")
            {
                return prefixID + "001";  // Fixwidth với độ dài mặc định
            }
            int nextID = int.Parse(lastID.Remove(0, prefixID.Length - 2)) + 1;
            int i = (int)Math.Log10(nextID);
            if (prefixID.Length > i + 1)
                prefixID = prefixID.ToString().Substring(0, prefixID.Length - i);
            else
                prefixID = prefixID.ToString().Substring(0, 2);
            return prefixID + nextID;
        }

    }
}
